package com.zy.studentSide.controller;

import com.zy.studentSide.entity.Student;
import com.zy.studentSide.entity.StudentInformation;
import com.zy.studentSide.service.IStudentService;
import com.zy.studentSide.service.Impl.IStudentInformationServiceImpl;
import com.zy.teacherSide.entity.Teacher;
import com.zy.util.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author huangdihua
 * @date 2021/12/27 10:02
 */
@RestController
public class StudentController {

    @Autowired
    private IStudentService iss;

    @Autowired
    private IStudentInformationServiceImpl isisi;

    /**
     * @param
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentLogin")
    public R studentLogin(@RequestBody Student student) {
        Student st = iss.studentLogin(student.getStudentNum(), student.getStudentPassword());
        return new R(st == null ? false : true, st);
    }

    /**
     * 学生注册接口
     * @param student
     * @return
     */
    @PostMapping
    @RequestMapping(value = "/studentRegister")
    public R studentRegister(@RequestBody Student student) {
        if(iss.getStudentById(student.getStudentNum()) != null) {
            return new R(false,null);
        }else{
            Integer id = RandomNum.getRandomID(6);
            Boolean b = true;
            while (b){
                //根据随机产生的id判断此id是否已经被使用，如果id!=null，说明此id存在被使用，且id的位数不是6位，再产生另外一个id
                if(iss.getStudentByStudentId(id) != null&&String.valueOf(id).length() != 6){
                    id=RandomNum.getRandomID(6);

                }else{
                    b=false;
                }
            }
            student.setStudentId(id);
            student.setStudentShiro(1);
            return new R(iss.save(student),student);
        }
    }

    /**
     * 逐个添加学生
     *
     * @param si
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/oneByOneSaveStudent/{teacherId}")
    public R oneByOneSaveStudent(@RequestBody StudentInformation si,@PathVariable Integer teacherId) {
        si.setTeacherId(teacherId);
        si.setStudentPhoto("xxxx");
        Integer id = RandomNum.getRandomID(6);
        Student st = new Student();
        st.setStudentId(id);
        st.setStudentName(si.getStudentName());
        st.setStudentNum(si.getStudentNum());
        st.setStudentPassword(String.valueOf(si.getStudentNum().substring(si.getStudentNum().length() - 6, si.getStudentNum().length())));
        st.setStudentShiro(2);
        return new R(isisi.save(si) && iss.save(st));
    }

    /**
     * 接受解析上传的文件
     *
     * @param file
     * @param request
     * @return R
     * @throws Exception
     */
    @ResponseBody
    @PostMapping
    @RequestMapping("/upload_studentInformation/{teacherId}")
    public R upload_excel(@RequestParam("file") MultipartFile file, HttpServletRequest request,@PathVariable Integer teacherId) throws Exception {
        if (!file.isEmpty()) {
            String webPath = request.getServletContext().getRealPath("");
            String filePath = "/resources/static/upload_file/";
            String fileName = DateUtil.formatDate(new Date(), "yyyyMMdd-HHmmssSSS") + "_" + file.getOriginalFilename();
            FileUtil.makeDirs(webPath + filePath);
            //保存服务器
            file.transferTo(new File(webPath + filePath + fileName));
            //解析
            List<StudentInformation> si_list = si_excel_to_clientInfo(teacherId,new File(webPath + filePath + fileName));
            //开始 上传 数据库
            for (StudentInformation s : si_list) {
                isisi.save(s);
            }
            //解析
            List<Student> s_list = s_excel_to_clientInfo(new File(webPath + filePath + fileName));
            //开始 上传 数据库
            for (Student s : s_list) {
                iss.save(s);
            }
            //删除用过的文件
            FileUtil.deleteFile(webPath + filePath + fileName);
        }

        return new R(true);
    }

    /**
     * 解析Excel，封装StudentInformation对象
     * @param userUploadFile
     * @return List<StudentInformation>
     * @throws ParseException
     */
    public List<StudentInformation> si_excel_to_clientInfo(Integer teacherId,File userUploadFile) throws ParseException {
        List<StudentInformation> list = new ArrayList<>();
        StudentInformation s1 = null;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            //获取第一个sheet页
            HSSFSheet sheet = wb.getSheetAt(0);
            if (sheet != null) {
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    HSSFRow row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //学号	姓名	  年龄	性别	  出生日期
                    s1 = new StudentInformation();
                    s1.setTeacherId(teacherId);
                    s1.setStudentNum(ExcelUtil.formatCell(row.getCell(0)));
                    s1.setStudentName(ExcelUtil.formatCell(row.getCell(1)));
                    s1.setStudentAge(Integer.parseInt(ExcelUtil.formatCell(row.getCell(2)).split("\\.")[0]));
                    s1.setStudentSex(ExcelUtil.formatCell(row.getCell(3)));
                    s1.setStudentPhoto("xxxx");
                    list.add(s1);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 解析Excel，封装Student对象
     * @param userUploadFile
     * @return List<Student>
     * @throws ParseException
     */
    public List<Student> s_excel_to_clientInfo(File userUploadFile) throws ParseException {
        List<Student> list = new ArrayList<>();
        Student s = null;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile));
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            //获取第一个sheet页
            HSSFSheet sheet = wb.getSheetAt(0);
            if (sheet != null) {
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    HSSFRow row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //学号	姓名	  年龄	性别	  出生日期
                    s = new Student();
                    Integer id = RandomNum.getRandomID(6);
                    s.setStudentId(id);
                    s.setStudentNum(ExcelUtil.formatCell(row.getCell(0)));
                    s.setStudentName(ExcelUtil.formatCell(row.getCell(1)));
                    String str = ExcelUtil.formatCell(row.getCell(0));
                    String pass = str.substring(str.length() - 6, str.length());

                    s.setStudentPassword(pass);
                    s.setStudentShiro(2);
                    list.add(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 下载导入学生信息的模板
     * @return ResponseEntity<byte[]>
     * @throws IOException
     */
    @PostMapping
    @RequestMapping(value="/student/excel_down")
    public ResponseEntity<Resource> excelExport(HttpServletResponse response) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/"+"student_import_model.xls");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new HSSFWorkbook(is);
            String fileName = "student_import_model.xls";
            ExcelUtil.downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);
    }

    /**
     * 教师端教师分页查看学生数据
     * @param currentPage
     * @param pageSize
     * @param teacherId
     * @return
     */
    @GetMapping
    @RequestMapping(value = "/getStudentByPage/{currentPage}/{pageSize}/{teacherId}")
    public R getStudentByPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize,@PathVariable Integer teacherId){
        return new R(true,isisi.getPage(currentPage,pageSize,teacherId));
    }

    /**
     * 教师编辑学生信息
     * @param si
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/teacherUploadStudentInformation")
    public R uploadStudentInformation(@RequestBody StudentInformation si){
        return new R(isisi.updateById(si));
    }

    /**
     * 教师删除学生信息
     * @param id
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/teacherDeleteStudentInformation/{id}")
    public R deleteStudentInformation(@PathVariable Integer id){
        return new R(isisi.removeById(id));
    }

}
